<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="资产设备名称" prop="assetName">
        <el-select
          v-model="queryParams.assetName"
          placeholder="请选择资产设备名称"
          clearable
          @change="handleQuery"
          style="width: 220px;"
        >
          <el-option
            v-for="(name, index) in uniqueAssetNames"
            :key="`${name}-${index}`"
            :label="name"
            :value="name"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="移动时间范围">
        <el-date-picker
          v-model="queryParams.timeRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          clearable
          style="width: 320px;"
          @clear="handleQuery"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['equ:stockin:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['equ:stockin:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['equ:stockin:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['equ:stockin:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="stockinList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="入库单id" align="center" prop="stockId" />
      <el-table-column label="资产设备名称" align="center" prop="assetName"/>
      <el-table-column label="资产编号" align="center" prop="assetNumber" />
      <el-table-column label="验收最终状态" align="center" prop="acceptanceStatus">
        <template slot-scope="scope">
          <el-tag :type="scope.row.acceptanceStatus === '验收通过' ? 'success' : 'danger'">
            {{ scope.row.acceptanceStatus }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="验收完成时间" align="center" prop="finishTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.finishTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['equ:stockin:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['equ:stockin:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px" class="view-form">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="入库单id" prop="stockId">
              <el-input v-model="form.stockId" placeholder="请输入入库单id" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="资产设备id" prop="assetId">
              <el-input v-model="form.assetId" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="资产编号" prop="assetNumber">
              <el-input v-model="form.assetNumber" placeholder="请输入资产编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="验收最终状态" prop="acceptanceStatus">
              <el-select v-model="form.acceptanceStatus" placeholder="请选择验收最终状态">
                <el-option label="通过" value="通过"></el-option>
                <el-option label="不通过" value="不通过"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="审批信息" prop="approvalInfo">
              <vue-json-editor
                v-model="approvalInfoJson"
                :options="jsonEditorOptions"
                class="json-editor no-dropdown no-dropdown"
                @input="handleJsonInput('approvalInfo', approvalInfoJson)"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="到货信息" prop="arrivalInfo">
              <vue-json-editor v-model="arrivalInfoJson" :options="jsonEditorOptions" class="json-editor no-dropdown" @input="handleJsonInput('arrivalInfo', arrivalInfoJson)"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="包装核查结果" prop="packageCheck">
              <vue-json-editor v-model="packageCheckJson" :options="jsonEditorOptions" class="json-editor no-dropdown" @input="handleJsonInput('packageCheck', packageCheckJson)"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="数量配件验收" prop="quantityCheck">
              <vue-json-editor v-model="quantityCheckJson" :options="jsonEditorOptions" class="json-editor no-dropdown" @input="handleJsonInput('quantityCheck', quantityCheckJson)"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="技术资料验收" prop="docCheck">
              <vue-json-editor v-model="docCheckJson" :options="jsonEditorOptions" class="json-editor no-dropdown" @input="handleJsonInput('docCheck', docCheckJson)"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="质量性能验收" prop="qualityCheck">
              <vue-json-editor v-model="qualityCheckJson" :options="jsonEditorOptions" class="json-editor no-dropdown" @input="handleJsonInput('qualityCheck', qualityCheckJson)"/>
            </el-form-item>
          </el-col>

          <!-- 审批记录仍使用表格形式 -->
          <el-col :span="24">
            <el-form-item label="审批记录" prop="approvalRecord">
              <el-table :data="approvalRecordList" style="width: 100%" border>
                <el-table-column label="姓名" width="180">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.name" placeholder="请输入姓名" />
                  </template>
                </el-table-column>
                <el-table-column label="部门" width="180">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.dept" placeholder="请输入部门" />
                  </template>
                </el-table-column>
                <el-table-column label="日期" width="180">
                  <template slot-scope="scope">
                    <el-date-picker clearable
                                    v-model="scope.row.date"
                                    type="date"
                                    value-format="yyyy-MM-dd"
                                    placeholder="请选择日期">
                    </el-date-picker>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="100" align="center">
                  <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-delete" @click="removeApprovalRecord(scope.$index)"></el-button>
                  </template>
                </el-table-column>
              </el-table>
              <div style="margin-top: 10px;">
                <el-button type="text" icon="el-icon-plus" size="mini" @click="addApprovalRecord">添加</el-button>
              </div>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="附件链接" prop="fileUrls">
              <file-upload v-model="form.fileUrls"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="验收完成时间" prop="finishTime">
              <el-date-picker clearable
                              v-model="form.finishTime"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="请选择验收完成时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listStockinVo, getStockin, delStockin, addStockin, updateStockin } from "@/api/equ/stockin";
import { getAllAssetName } from "@/api/equ/asset";
import VueJsonEditor from 'vue-json-editor';

export default {
  name: "Stockin",
  components: {
    VueJsonEditor
  },
  data() {
    return {
      loading: true,
      stockinList: [],
      total: 0,
      title: "",
      open: false,
      single: true,
      multiple: true,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        assetName: undefined,
        timeRange: []
      },
      form: {
        stockId: null,
        assetId: null,
        assetNumber: null,
        acceptanceStatus: '验收通过',
        approvalInfo: {},
        arrivalInfo: {},
        packageCheck: {},
        quantityCheck: {},
        docCheck: {},
        qualityCheck: {},
        approvalRecord: null,
        finishTime: null,
        fileUrls: null,
        remark: null,
      },
      rules: {
        stockId: [
          { required: true, message: "入库单id不能为空", trigger: "blur" }
        ],
        assetId: [
          { required: true, message: "资产设备id不能为空", trigger: "blur" }
        ],
        assetNumber: [
          { required: true, message: "资产编号不能为空", trigger: "blur" }
        ],
        acceptanceStatus: [
          { required: true, message: "请选择验收最终状态", trigger: "change" }
        ],
        approvalInfo: [
          { required: true, message: "审批信息不能为空", trigger: "change", type: 'object' }
        ],
        arrivalInfo: [
          { required: true, message: "到货信息不能为空", trigger: "change", type: 'object' }
        ],
        packageCheck: [
          { required: true, message: "包装核查结果不能为空", trigger: "change", type: 'object' }
        ],
        quantityCheck: [
          { required: true, message: "数量配件验收不能为空", trigger: "change", type: 'object' }
        ],
        docCheck: [
          { required: true, message: "技术资料验收不能为空", trigger: "change", type: 'object' }
        ],
        qualityCheck: [
          { required: true, message: "质量性能验收不能为空", trigger: "change", type: 'object' }
        ],
      },
      approvalRecordList: [{ name: '', dept: '', date: '' }],
      uniqueAssetNames: [],

      approvalInfoJson: {},
      arrivalInfoJson: {},
      packageCheckJson: {},
      quantityCheckJson: {},
      docCheckJson: {},
      qualityCheckJson: {},

      jsonEditorOptions: {
        mode: 'form',
        expanded: true,
        showBtn: false,
        indentation: 2,
        mainMenuBar: false
      },
      currentFileKey: 'unknownFiles',
    };
  },
  created() {
    this.getList();
    this.getAllAssetName();
  },
  methods: {
    getList() {
      this.loading = true;
      listStockinVo(this.queryParams).then(response => {
        this.stockinList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    getAllAssetName() {
      getAllAssetName().then(response => {
        this.uniqueAssetNames = response.data || [];
      });
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.queryParams.assetName = undefined;
      this.queryParams.timeRange = [];
      this.handleQuery();
    },
    handleSelectionChange(selection) {
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加验收入库";
      this.approvalInfoJson = {
        steps: [
          { dept: '', approver: '', result: '待审批', date: '' }
        ]
      };
    },
    handleUpdate(row) {
      this.reset();
      getStockin(row.stockId).then(response => {
        const data = response.data;
        this.form = {
          ...response.data,
          approvalInfo: data.approvalInfo ? JSON.parse(data.approvalInfo) : {},
          arrivalInfo: data.arrivalInfo ? JSON.parse(data.arrivalInfo) : {},
          packageCheck: data.packageCheck ? JSON.parse(data.packageCheck) : {},
          quantityCheck: data.quantityCheck ? JSON.parse(data.quantityCheck) : {},
          docCheck: data.docCheck ? JSON.parse(data.docCheck) : {},
          qualityCheck: data.qualityCheck ? JSON.parse(data.qualityCheck) : {},
        };
        this.approvalInfoJson = this.form.approvalInfo;
        this.arrivalInfoJson = this.form.arrivalInfo;
        this.packageCheckJson = this.form.packageCheck;
        this.quantityCheckJson = this.form.quantityCheck;
        this.docCheckJson = this.form.docCheck;
        this.qualityCheckJson = this.form.qualityCheck;

        this.parseApprovalRecord(response.data.approvalRecord);
        this.currentFileKey = response.data.fileUrls ? Object.keys(JSON.parse(response.data.fileUrls))[0] : 'unknownFiles';

        this.open = true;
        this.title = "修改验收入库";
      });
    },
    submitForm() {
      this.$refs["formRef"].validate(valid => {
        if (valid) {
          const formToSubmit = {
            ...this.form,
            approvalInfo: JSON.stringify(this.form.approvalInfo),
            arrivalInfo: JSON.stringify(this.form.arrivalInfo),
            packageCheck: JSON.stringify(this.form.packageCheck),
            quantityCheck: JSON.stringify(this.form.quantityCheck),
            docCheck: JSON.stringify(this.form.docCheck),
            qualityCheck: JSON.stringify(this.form.qualityCheck),
            approvalRecord: this.convertApprovalRecordToJson(),
            fileUrls: this.formatFileUrlsForApi(this.form.fileUrls),
          };

          if (this.form.stockId != null) {
            updateStockin(formToSubmit).then(() => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addStockin(formToSubmit).then(() => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handleDelete(row) {
      this.$modal.confirm('是否确认删除入库单编号为"' + row.stockId + '"的数据项？').then(() => {
        return delStockin(row.stockId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    handleExport() {
      this.download('equ/stockin/export', { ...this.queryParams }, `stockin_${new Date().getTime()}.xlsx`);
    },
    handleJsonInput(fieldName, jsonObject) {
      this.form[fieldName] = jsonObject;
    },
    addApprovalRecord() {
      this.approvalRecordList.push({ name: '', dept: '', date: '' });
    },
    removeApprovalRecord(index) {
      if (this.approvalRecordList.length > 1) {
        this.approvalRecordList.splice(index, 1);
      } else {
        this.$modal.msgWarning("审批记录至少保留一条");
      }
    },
    convertApprovalRecordToJson() {
      return JSON.stringify(this.approvalRecordList);
    },
    parseApprovalRecord(jsonStr) {
      if (jsonStr) {
        this.approvalRecordList = JSON.parse(jsonStr);
      } else {
        this.approvalRecordList = [{ name: '', dept: '', date: '' }];
      }
    },
    formatFileUrlsForApi(urls) {
      if (!urls) return JSON.stringify({ [this.currentFileKey]: [] });
      return JSON.stringify({ [this.currentFileKey]: urls.split(',') });
    },
    reset() {
      this.form = {
        stockId: null,
        assetId: null,
        assetNumber: null,
        acceptanceStatus: '验收通过',
        approvalInfo: {},
        arrivalInfo: {},
        packageCheck: {},
        quantityCheck: {},
        docCheck: {},
        qualityCheck: {},
        approvalRecord: null,
        finishTime: null,
        fileUrls: null,
        remark: null,
      };
      this.approvalInfoJson = {};
      this.arrivalInfoJson = {};
      this.packageCheckJson = {};
      this.quantityCheckJson = {};
      this.docCheckJson = {};
      this.qualityCheckJson = {};

      this.approvalRecordList = [{ name: '', dept: '', date: '' }];
      this.currentFileKey = 'unknownFiles';
      this.$refs["formRef"]?.clearValidate();
    },
    cancel() {
      this.open = false;
      this.reset();
    },
  }
};
</script>

<style scoped>
.view-form {
  max-height: 60vh;
  overflow-y: auto;
  padding-right: 10px;
}
.json-editor {
  min-height: 180px;
  font-size: 14px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}
/* 统一的 JSON 编辑器清理样式 */
.no-dropdown >>> .jsoneditor-menu,         /* 隐藏顶部下拉菜单 */
.no-dropdown >>> .jsoneditor-search,       /* 隐藏搜索框 */
.no-dropdown >>> .jsoneditor-dragarea  /* 隐藏拖拽控件 */
{
  display: none !important;
}
</style>
